var express = require('express');
var router = express.Router();

var ObjectId = require('mongodb').ObjectId;
var mongodbModel = require('./mongodbModel');
var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();

var articleList = new mongodbModel('blog', 'article');
var Article = new mongodbModel('blog', 'articles');
var mySelf = new mongodbModel('blog', 'Myself');
var tag = new mongodbModel('blog', 'tag');
var link = new mongodbModel('blog', 'link');


articleList.init();
Article.init();
mySelf.init();
tag.init();
link.init()


/* GET users listing. */
router.get('/article/list', function (req, res, next) {
    let params = {}
    if (String(req.query.sort) && req.query.order) {
        params.sortBy = String(req.query.sort)
        params.order = req.query.order - 0
    }
    if (req.query.page && req.query.size) {
        params.page = req.query.page - 0
        params.size = req.query.size - 0
    }
    articleList.find({}, params).then(
        (data) => {
            res.status(200).json(data)
        }
    ).catch();
});
router.post('/article/add', function (req, res, next) {
    var articleId = Date.now();
    var articleInfo = {
        title: req.body.title,
        desc: req.body.desc,
        auth: req.body.auth,
    };

    for (item in articleInfo) {
        if (!articleInfo[item]) {
            res.json({
                msg: `${item} is required`
            })
        }
    }

    articleInfo = {
        created_time: new Date(),
        updated_time: new Date(),
        article_id: articleId,
        hidden: req.body.hidden || false,
        category: (req.body.category || '').split(','),
        view_count: 0,
        ...articleInfo
    };
    articleInfo.hidden = (articleInfo.hidden === "true")

    var article = {
        article_id: articleId,
        content: req.body.content || ''
    };
    Promise.all([articleList.insert(articleInfo), Article.insert(article)])
        .then(
            ([a, b]) => {
                res.json([a, b])
            }
        ).catch()
});
router.post('/article/update', function (req, res, next) {
    if (!req.body.article_id) {
        res.json({
            msg: 'articleId is required'
        })
    }

    var cache = []
    if (req.body.title) {
        var articleInfo = {
            title: req.body.title,
            desc: req.body.desc,
            auth: req.body.auth,
        };
        for (item in articleInfo) {
            if (!articleInfo[item]) {
                res.json({
                    msg: `${item} is required`
                })
            }
        }
        articleInfo = {
            updated_time: new Date(),
            hidden: req.body.hidden || false,
            category: (req.body.category || '').split(','),
            view_count: req.body.view_count || 0,
            ...articleInfo
        };
        articleInfo.hidden = (articleInfo.hidden === "true")
        cache.push(articleList.update({article_id: req.body.article_id - 0}, {$set: articleInfo}))
    }

    if (req.body.content) {
        var article = {
            content: req.body.content || ''
        };
        cache.push(Article.update({article_id: req.body.article_id - 0}, {$set: article}))
    }

    Promise.all(cache).then(data => {
        res.json(data)
    }).catch()

});
router.post('/article/remove', function (req, res, next) {
    if (!req.body.article_id) {
        res.json({
            msg: 'articleId is required'
        })
    } else {
        Promise.all([articleList.remove({article_id: req.body.article_id - 0}), Article.remove({article_id: req.body.article_id - 0})])
            .then(([a, b]) => {
                res.json([a, b])
            }).catch()
    }
});

router.get('/article/read', function (req, res, next) {
    if (!req.query.article_id) {
        res.json({
            msg: 'article_id is required'
        })
    } else {
        Article.find({article_id: req.query.article_id - 0}).then(
            (data) => {
                res.json(data)
            }
        ).catch(
            err => {
                res.json(err)
            }
        );
    }
});


router.get('/tag/list', function (req, res, next) {
    tag.find({}, {sortBy: 'order', order: 1}).then(data => {
        res.json(data)
    }).catch()
});
router.post('/tag/add', function (req, res, next) {
    if (!req.body.name || !req.body.order) {
        res.json({
            msg: `name and id is required `
        })
    }
    if (req.body._id) {
        tag.update({_id: ObjectId(req.body._id)}, {
            $set: {
                name: req.body.name,
                order: req.body.order
            }
        }).then(x => {
            res.json(x)
        }).catch()
    } else {
        tag.insert({
            name: req.body.name,
            order: req.body.order
        }).then(data => {
            res.json(data)
        }).catch();
    }

});
/*router.post('/tag/update', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    tag.update({_id: ObjectId(req.body._id)}, {
        $set: {
            name: req.body.name,
            order: req.body.order
        }
    }).then(x => {
        res.json(x)
    }).catch()
});*/
router.post('/tag/remove', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    tag.remove({_id: ObjectId(req.body._id)}).then(x => {
        res.json(x);
    }).catch()
});


router.get('/link/list', function (req, res, next) {
    link.find().then(data => {
        res.json(data)
    }).catch()
});
router.post('/link/add', function (req, res, next) {
    if (!req.body.name || !req.body.link) {
        res.json({
            msg: `name and href order is required `
        })
    }
    if (req.body._id) {
        link.update({_id: ObjectId(req.body._id)}, {
            $set: {
                name: req.body.name,
                order: req.body.order,
                link: req.body.link
            }
        }).then(x => {
            res.json(x)
        }).catch()
    } else {
        link.insert({
            name: req.body.name,
            order: req.body.order || 0,
            link: req.body.link
        }).then(data => {
            res.json(data)
        }).catch();
    }

});
/*router.post('/link/update', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    link.update({_id: ObjectId(req.body._id)}, {
        $set: {
            name: req.body.name,
            order: req.body.order,
            link: req.body.link
        }
    }).then(x => {
        res.json(x)
    }).catch()
});*/


router.post('/link/remove', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    link.remove({_id: ObjectId(req.body._id)}).then(x => {
        res.json(x)
    }).catch()
});


router.get('/info/basic', function (req, res, next) {
    mySelf.find().then(data => {
        res.json({
            _id: data[0]._id,
            name: data[0].name,
            direction: data[0].direction,
            motto: data[0].motto,
            address: data[0].address
        });
    }).catch()
});
router.get('/info/all', function (req, res, next) {
    mySelf.find().then(data => {
        res.json(data[0])
    }).catch()
});
router.post('/info/update', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    mySelf.update({_id: ObjectId(req.body._id)}, {
        $set: {
            name: req.body.name || '',
            direction: req.body.direction || '',
            motto: req.body.motto || '',
            address: (req.body.address || '').split(',')
        }
    }).then(data => {
        res.json(data)
    }).catch();
});

router.post('/about/update', function (req, res, next) {
    if (!req.body._id) {
        res.json({
            msg: `_id is required `
        })
    }
    mySelf.update({_id: ObjectId(req.body._id)}, {
        $set: {
            content: req.body.content
        }
    }).then(data => {
        res.json(data)
    }).catch();
});

router.get('/user/logout', function (req, res, next) {
    res.status(200).cookie("userId", '', {
        path: '/',
        maxAge: -1
    }).json({
        yy: new Date()
    })
})
router.post('/user/login', function (req, res, next) {
    var id = [...req.body.id].reverse().join('');
    var password = req.body.password
    if (id === password) {
        res.status(200).cookie("userId", id, {
            path: '/',
            maxAge: 1000 * 60 * 60
        }).json({
            status: 1,
            name: req.body.id
        })
    } else {
        res.status(200).json({
            msg: 'error',
            status: 0
        })
    }
})


/*router.post('/upload/file', multipartMiddleware, function (req, res) {
    console.log(req.body, req.files);
    var file = req.file
    var file = file.path + file.originalFilename;
    console.log()
});*/


module.exports = router;